import os,sys
from PySide6.QtWidgets import QStackedWidget, QPushButton
from PySide6.QtCore import Qt, QSize, Signal, QObject
from PySide6.QtGui import QIcon

class Router(QObject):
    """统一管理模块注册、实例化、切换"""

    module_changed = Signal(str)

    def __init__(self, stacked_widget: QStackedWidget, button_layout, server_manager):
        super().__init__()
        self.stacked_widget = stacked_widget
        self.button_layout = button_layout
        self.server_manager = server_manager
        self.modules = {}  
        self.buttons = {}  

    def resource_path(self, relative_path: str):
        """打包路径"""
        if getattr(sys, 'frozen', False):
            base_path = sys._MEIPASS
        else:
            base_path = os.path.dirname(os.path.dirname(__file__)) 
        return os.path.join(base_path, relative_path)

    def register(self, name: str, module_class, icon_path=None):
        """注册并实例化模块"""
        widget = module_class(server_manager=self.server_manager)
        self.modules[name] = widget
        self.stacked_widget.addWidget(widget)

        btn = QPushButton(name)
        btn.setObjectName("sidebarBtn") 
        btn.setCheckable(True)
        btn.setCursor(Qt.PointingHandCursor)

        if icon_path:
            abs_icon = self.resource_path(icon_path)
            if abs_icon:
                btn.setIcon(QIcon(abs_icon))
                btn.setIconSize(QSize(18, 18))

        btn.clicked.connect(lambda checked, n=name: self.activate(n))
        self.button_layout.addWidget(btn)
        self.buttons[name] = btn

    def activate(self, name):
        """切换当前模块"""
        if name not in self.modules:
            return
        for n, btn in self.buttons.items():
            btn.setChecked(n == name)

        self.stacked_widget.setCurrentWidget(self.modules[name])
        self.current_module = self.modules[name]

        self.module_changed.emit(name)

    def get_module(self, name):
        return self.modules.get(name)
